<!-- 藏品初编基本信息组件 -->
<script lang="ts" setup>
import {
  type FormInst,
  NButton,
  NSelect,
  NFormItem,
  type SelectOption,
  NInput,
  useMessage,
  type UploadFileInfo,
  NSpace,
  NForm,
  NDatePicker,
  NTreeSelect
} from 'naive-ui'
import { ref, shallowRef, watch, type Ref, nextTick, reactive, computed } from 'vue'
import VUpload from '@/views/OA/Common/Upload.vue'
import { useRoute } from 'vue-router'
import type { CTSelectOption } from '@/api/collection'
import { sendRequest } from '@/utils/api'
import type { HttpResponse, JsonHttpResponse } from '@/utils/http'
import UploadFileV2 from '@/views/common/UploadFileV2.vue'
import type { DicTreeModel } from '@/api/dic'
import FileList from '@/components/FileList.vue'
import { keysOf } from '@/utils/object'
import VAttachments from '@/views/OA/Common/Attachments.vue'
const props = defineProps({
  id: { type: String, default: () => null },
  typeShow: { type: Number, default: () => 0 },
  code: { type: String, default: () => null }
})

const emit = defineEmits(['flush'])

const formData = ref({} as any)
const formRef = ref<FormInst | null>(null)
const formRef2 = ref<FormInst | null>(null)
const datetime = computed<any>({
  get() {
    return formData.value.receiveTime
  },
  set(v) {
    formData.value.receiveTime = v
  }
})
const datetimeT = computed<any>({
  get() {
    return formData.value.startDate?.split(' ')?.[0]
  },
  set(v) {
    formData.value.startDate = v
  }
})
const datetimeEnd = computed<any>({
  get() {
    return formData.value.endDate?.split(' ')?.[0]
  },
  set(v) {
    formData.value.endDate = v
  }
})
const message = useMessage()
const route = useRoute()
const isUpdate = false
const isDetail = true
const rules = {}
// const rules = {
//   collectTypeCode: {
//     required: true,
//     message: '请选择征集方式',
//     trigger: ['change', 'blur']
//   },
//   receiveTime: {
//     required: true,
//     message: '请选择接收时间',
//     trigger: ['change', 'blur']
//   },
//   receiveUser: {
//     required: true,
//     message: '请输入接收人',
//     trigger: ['change', 'blur','input']
//   },
//   transferUser: {
//     required: true,
//     message: '请输入移交人',
//     trigger: ['change', 'blur','input']
//   },
//   supervisor:{
//     required: true,
//     message: '请输入督交人',
//     trigger: ['change', 'blur','input']
//   },
//   itemName: {
//     required: true,
//     message: '请输入名称',
//     trigger: ['change', 'blur']
//   },
//   itemNum: {
//     required: true,
//     message: '请输入数量',
//     trigger: ['change', 'blur','input']
//   }
// }
// 附件
const handleUploadList = (v: any) => (formData.value.imgIds = v)
const createQuerySelectOptions = (
  options: Ref<CTSelectOption[]>,
  loading: Ref<boolean>,
  onFinish?: () => void
) => {
  return async (parentCode?: string) => {
    try {
      loading.value = true
      const [error, res] = await sendRequest<HttpResponse<CTSelectOption[]>>({
        module: 'collection',
        api: 'typeSelectByCode',
        override: {
          params: {
            parentCode: parentCode || null
          }
        }
      })
      if (error) throw error
      if (res.code !== 0) throw new Error(res.msg)
      options.value = res.data
      onFinish?.()
    } catch (error) {
      console.log(error)
    } finally {
      loading.value = false
    }
  }
}
const createAutoSelectFirstItem = (value: Ref<string | null>, options: Ref<CTSelectOption[]>) => {
  return () => {
    if (options.value.length > 0) {
      value.value = options.value[0].value
    }
  }
}
const createCascader = (
  configs: {
    value: Ref<string | null>
    options: Ref<CTSelectOption[]>
    loading: Ref<boolean>
    autoSelectFirst: boolean
    onFinish?: () => void
  }[]
) => {
  const queryFuncList = configs.map((config) => {
    const autoSelect = config.autoSelectFirst
      ? createAutoSelectFirstItem(config.value, config.options)
      : undefined
    return createQuerySelectOptions(config.options, config.loading, () => {
      autoSelect?.()
      config.onFinish?.()
    })
  })

  for (let i = 0; i < configs.length - 1; i++) {
    if (!configs[i + 1]) continue

    watch(
      configs[i].value,
      (v) => {
        configs[i + 1].options.value = []
        configs[i + 1].value.value = null
        if (!v) return
        queryFuncList[i + 1](v)
      },
      { immediate: true }
    )
  }

  return queryFuncList[0]
}

const oneSelectValue = ref<string | null>(null)
const oneSelectOptions = shallowRef<CTSelectOption[]>([])
const oneSelectLoading = ref(false)

const twoSelectValue = ref<string | null>(null)
const twoSelectOptions = shallowRef<CTSelectOption[]>([])
const twoSelectLoading = ref(false)

const threeSelectValue = ref<string | null>(null)
const threeSelectOptions = shallowRef<CTSelectOption[]>([])
const threeSelectLoading = ref(false)

const isUseLastSelect = ref(true)
const cascader = createCascader([
  {
    value: oneSelectValue,
    options: oneSelectOptions,
    loading: oneSelectLoading,
    autoSelectFirst: false
  },
  {
    value: twoSelectValue,
    options: twoSelectOptions,
    loading: twoSelectLoading,
    autoSelectFirst: false
  },
  {
    value: threeSelectValue,
    options: threeSelectOptions,
    loading: threeSelectLoading,
    autoSelectFirst: false,
    onFinish: () => (isUseLastSelect.value = threeSelectOptions.value.length > 0)
  }
])

//去除空格
const change1 = (v: any) => {
  formData.value.receiveUser = v.trim()
}
const change2 = (v: any) => {
  formData.value.deliveryUnit = v.trim()
}
const change3 = (v: any) => {
  formData.value.transferUser = v.trim()
}
const change4 = (v: any) => {
  formData.value.transferUserPhone = v.trim()
}
const change5 = (v: any) => {
  formData.value.supervisor = v.trim()
}
const change6 = (v: any) => {
  formData.value.itemName = v.trim()
}
const change7 = (v: any) => {
  formData.value.itemNum = v.trim()
}
const change8 = (v: any) => {
  formData.value.specifications = v.trim()
}
const change9 = (v: any) => {
  formData.value.materialQuality = v.trim()
}
const change10 = (v: any) => {
  formData.value.binding = v.trim()
}
const change11 = (v: any) => {
  formData.value.appearance = v.trim()
}
const change12 = (v: any) => {
  formData.value.depositTerm = v.trim()
}
const change13 = (v: any) => {
  formData.value.press = v.trim()
}
const change14 = (v: any) => {
  formData.value.language = v.trim()
}
const change15 = (v: any) => {
  formData.value.notes = v.trim()
}
const change16 = (v: any) => {
  formData.value.depositTerm = v.trim()
}

const isTrue = ref(false)
const changeTree = (v: any) => {
  formData.value.collectTypeCode = v
  if (formData.value.collectTypeCode === 'A3007') {
    isTrue.value = true
  } else {
    isTrue.value = false
  }
}
const clueMethodOptions = reactive<DicTreeModel[]>([])
const queryClueMethodOptions = async () => {
  try {
    const [error, res] = await sendRequest<HttpResponse<DicTreeModel[]>>({
      module: 'dic',
      api: 'getTree',
      override: {
        params: {
          dicCode: 'A30'
        }
      }
    })

    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    clueMethodOptions.length = 0
    clueMethodOptions.push(...(res.data[0] ? res.data[0].children || [] : []))
  } catch (error) {
    console.error(error)
  }
}
const fileList = ref<UploadFileInfo[]>([])
const fileListImg = ref<UploadFileInfo[]>([])
const handleUpdateFileList = (e: UploadFileInfo[]) => {
  fileList.value = e
}
const validatorTypeFormItem = () => {
  if (isUseLastSelect.value) return threeSelectValue.value !== null
  return twoSelectValue.value !== null
}
const clueInfoLoading = ref(false)
const checkIsDetail = async (code: any) => {
  if (!isDetail && !isUpdate) return

  try {
    clueInfoLoading.value = true
    const [error, res] = await sendRequest<HttpResponse>({
      module: 'collectProcess',
      api: 'info',
      uri: {
        itemCode: code as string
      }
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    const { data } = res

    keysOf(data).forEach((e) => {
      {
        formData.value[e] = data[e] as never
      }
    })
    if (formData.value.collectTypeCode === 'A3007') {
      isTrue.value = true
    } else {
      isTrue.value = false
    }

    if (isUpdate) {
      cascader()
    }
    fileListImg.value = data.imgFileList
    fileList.value = data.fileList?.map((e: any, i: number) => {
      const f = new File([e.name], e.name, { type: e.type })
      // @ts-ignore
      f.remoteId = e.id
      return {
        id: i,
        name: e.name,
        file: f,
        status: 'finished',
        url: e.path,
        remoteId: e.id
      }
    })
  } catch (error) {
    console.error(error)
  } finally {
    setTimeout(() => {
      clueInfoLoading.value = false
    }, 2000)
  }
}

// onMounted(() => {
//   if (!isDetail && !isUpdate) cascader()
//   queryClueMethodOptions()
//   checkIsDetail()
// })
watch(
  () => props.id,
  () => {
    sendRequest({
      module: 'collectProcess',
      api: 'collectingItemsInfo',
      uri: {
        id: props.id
      }
    }).then(async ([err, res]) => {
      if (err) return
      // keysOf(res.data).forEach((e) => {
      //   form[e] = res.data[e] as never
      // })
      //
      queryClueMethodOptions()
      await checkIsDetail(res.data?.itemCode)
      nextTick(() => {
        emit('flush')
      })
      // queryMenuOptions(role.id)
    })
  },
  {
    immediate: true
  }
)
// onMounted(async () => {
//   // 修改回显
//   if (props.id) {
//     sendRequest({
//       module: 'collectProcess',
//       api: 'collectingItemsInfo',
//       uri: {
//         id: props.id
//       }
//     }).then(([err, res]) => {
//       if (err) return
//       // keysOf(res.data).forEach((e) => {
//       //   form[e] = res.data[e] as never
//       // })
//
//       checkIsDetail(res.data?.itemCode)
//       // queryMenuOptions(role.id)
//     })
//   }
// })
</script>

<template>
  <DetailFormProvider :disabled="!isDetail">
    <div class="add-collect">
      <div class="ac-title">征集信息</div>
      <div
        class="ac-card"
        style="padding-bottom: 0"
      >
        <NForm
          ref="formRef2"
          :model="formData"
          require-mark-placement="left"
          :rules="rules"
          label-placement="left"
          :label-width="140"
          label-align="right"
          :disabled="isDetail"
        >
          <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 0 30px">
            <NFormItem
              label="征集方式:"
              path="collectTypeCode"
            >
              <NTreeSelect
                :options="clueMethodOptions"
                v-model:value="formData.collectTypeCode"
                placeholder="请选择征集方式"
                clearable
                style="width: 100%;'"
                key-field="code"
                label-field="name"
                @update-value="changeTree"
              />
            </NFormItem>
            <NFormItem
              label="接收时间:"
              path="receiveTime"
            >
              <NInput
                v-model:value="datetime"
                placeholder="请输入接收人"
                @update:value="change1"
                style="width: 100%;'"
              />
              <!-- <NDatePicker
              input-readonly
              v-model:formatted-value="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetime"
              default-time="00:00:00"
              style="width: 100%"
              placeholder="请选择接收时间"
            /> -->
            </NFormItem>
          </div>
          <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 0 30px">
            <NFormItem
              label="接收人:"
              path="receiveUser"
            >
              <NInput
                v-model:value="formData.receiveUser"
                placeholder="请输入接收人"
                @update:value="change1"
                style="width: 100%;'"
              />
            </NFormItem>
            <NFormItem
              label="交送单位:"
              path="deliveryUnit"
            >
              <NInput
                v-model:value="formData.deliveryUnit"
                placeholder="请输入交送单位"
                @update:value="change2"
                style="width: 100%"
              />
            </NFormItem>
          </div>
          <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 0 30px">
            <NFormItem
              label="移交人:"
              path="transferUser"
            >
              <NInput
                v-model:value="formData.transferUser"
                placeholder="请输入移交人"
                @update:value="change3"
                style="width: 100%;'"
              />
            </NFormItem>
            <NFormItem
              label="移交人联系方式:"
              path="transferUserPhone"
            >
              <NInput
                v-model:value="formData.transferUserPhone"
                placeholder="输入移交人联系方式"
                style="width: 100%"
                @update:value="change4"
              />
            </NFormItem>
          </div>
          <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 0 30px">
            <NFormItem
              label="督交人:"
              path="supervisor"
            >
              <NInput
                v-model:value="formData.supervisor"
                placeholder="请输入督交人"
                style="width: 100%"
                @update:value="change5"
              />
            </NFormItem>
            <NFormItem
              label=""
              path=""
            >
              <!-- <NInput
                v-model:value="formData.supervisor"
                placeholder="请输入督交人"
                style="width: 100%;"
                @update:value="change5"
              /> -->
            </NFormItem>
          </div>
        </NForm>
      </div>
      <!-- <div class="br"></div> -->

      <div class="ac-title">物品信息</div>
      <div
        class="ac-card"
        style="padding-bottom: 0"
      >
        <NForm
          ref="formRef"
          :model="formData"
          :rules="rules"
          label-placement="left"
          :label-width="140"
          require-mark-placement="left"
          label-align="right"
          :disabled="isDetail"
        >
          <div>
            <NFormItem
              label="类型："
              path="type"
              :rule="
                !isDetail && (!isUpdate || (isUpdate && !formData.itemTypeName))
                  ? {
                      required: true,
                      message: '类型必填',
                      validator: () => validatorTypeFormItem()
                    }
                  : undefined
              "
            >
              <NInput
                disabled
                :value="formData.itemTypeName"
                style="width: 100%"
              />
            </NFormItem>
          </div>
          <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 0 30px">
            <NFormItem
              label="名称:"
              path="itemName"
            >
              <NInput
                v-model:value="formData.itemName"
                placeholder="输入名称"
                @update:value="change6"
                style="width: 100%;'"
              />
            </NFormItem>
            <NFormItem
              label="数量:"
              path="itemNum"
            >
              <NInput v-model:value="formData.itemNum" placeholder="输入数量" style="width: 100%"
              showButton: false @update:value="change7"/>
            </NFormItem>
          </div>
          <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 0 30px">
            <NFormItem
              label="规格:"
              path="specifications"
            >
              <NInput
                v-model:value="formData.specifications"
                placeholder="请输入规格"
                clearable
                @update:value="change8"
                style="width: 100%;'"
              />
            </NFormItem>
            <NFormItem
              label="材质:"
              path="materialQuality"
            >
              <NInput
                v-model:value="formData.materialQuality"
                placeholder="输入材质"
                @update:value="change9"
                style="width: 100%"
              />
            </NFormItem>
          </div>
          <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 0 30px">
            <NFormItem
              label="装帧:"
              path="binding"
            >
              <NInput
                v-model:value="formData.binding"
                placeholder="请输入装帧"
                @update:value="change10"
                style="width: 100%;'"
              />
            </NFormItem>
            <NFormItem
              label="品相:"
              path="appearance"
            >
              <NInput
                v-model:value="formData.appearance"
                placeholder="请输入品相"
                @update:value="change11"
                style="width: 100%"
              />
            </NFormItem>
          </div>
          <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 0 30px">
            <NFormItem
              label="年代:"
              path="depositTerm"
            >
              <NInput
                v-model:value="formData.depositTerm"
                placeholder="请输入年代"
                @update:value="change12"
                style="width: 100%;'"
              />
            </NFormItem>
            <NFormItem
              label="出版社:"
              path="press"
            >
              <NInput
                v-model:value="formData.press"
                placeholder="请输入出版社"
                style="width: 100%"
                @update:value="change13"
              />
            </NFormItem>
          </div>
          <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 0 30px">
            <NFormItem
              label="语种:"
              path="language"
            >
              <NInput
                v-model:value="formData.language"
                placeholder="请输入语种"
                @update:value="change14"
                style="width: 100%;'"
              />
            </NFormItem>
            <NFormItem
              label="备注:"
              path="notes"
            >
              <NInput
                v-model:value="formData.notes"
                placeholder="请输入备注"
                style="width: 100%"
                @update:value="change15"
                type="textarea"
                :autosize="{
                  minRows: 1,
                  maxRows: 5
                }"
              />
            </NFormItem>
          </div>
          <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 0 30px">
            <NFormItem
              label="开始时间:"
              path="startDate"
              v-show="isTrue"
            >
              <NDatePicker
                input-readonly
                v-model:formatted-value="datetimeT"
                value-format="yyyy-MM-dd"
                type="date"
                style="width: 100%;'"
                placeholder="输入开始时间"
              />
            </NFormItem>
            <NFormItem
              label="结束时间:"
              path="endDate"
              v-show="isTrue"
            >
              <NDatePicker
                input-readonly
                v-model:formatted-value="datetimeEnd"
                value-format="yyyy-MM-dd"
                type="date"
                style="width: 100%"
                placeholder="输入结束时间"
              />
            </NFormItem>
          </div>
          <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 0 30px">
            <NFormItem
              label="代存期限:"
              path="depositTerm"
              v-show="isTrue"
            >
              <NInput
                v-model:value="formData.depositTerm"
                placeholder="请输入代存期限"
                @update:value="change16"
                style="width: 100%;'"
              />
            </NFormItem>
            <!-- <NFormItem
            label="图片:"
            path="fileIds"
          >
            <VUpload
              :file-list="fileListImg"
              @getList="handleUploadList"
              style="width: 100%"
              v-show="!isDetail"
            />
            <VAttachments
              v-else
              :attach-list="formData.imgFileList"
            ></VAttachments>
          </NFormItem> -->
          </div>
        </NForm>

        <!-- <div class="br"></div> -->
        <!-- <div class="ac-title">其他信息</div>
      <NFormItem
        label="附件："
        label-placement="left"
      >
        <UploadFileV2
          v-show="!isDetail"
          :file-list="fileList"
          :disabled="isDetail"
          @update:file-list="handleUpdateFileList"
        >
          <template #trigger="{ handleClick }">
            <n-button
              @click="handleClick"
              color="#6CB187"
              ghost
              size="small"
            >
              点击上传
            </n-button>
          </template>
        </UploadFileV2>
        <FileList
          v-else
          :file-list="fileList"
        />
      </NFormItem> -->
      </div>
    </div>
  </DetailFormProvider>
</template>
<style scoped lang="scss">
.add-collect {
  width: 100%;

  // min-height: 100%;
  padding: 15rem 0 30rem;
  // background-color: #f0efee;

  .br {
    position: relative;
    width: 100%;
    padding: 30rem 0;

    &::after {
      content: '';
      position: absolute;
      width: 100%;
      top: 50%;
      left: 0;
      border-top: 1px dotted #bc9e70;
      transform: translateY(-50%);
    }
  }

  .ac-card {
    padding: 20rem;
    // background-color: #e1e1e1;
  }
  .ac-title {
    font-size: 22px;
    font-family: PingFangSC, PingFang SC;
    font-weight: 500;
    color: #5fb17f;
    margin-bottom: 10rem;
  }
}

.add-collect-buttons {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0 16rem;

  .n-button:not(.back) {
    width: 100rem;
    height: 50rem;
  }

  &.start {
    justify-content: flex-start;
  }
}
</style>
